<?php

namespace iBrand\Shop\Server\Controllers\V2;

use iBrand\Common\Controllers\Controller;
use iBrand\Shop\Core\Models\O2oGoodsProducts;
use iBrand\Shop\Core\Repositories\ClerkRepository;
use iBrand\Shop\Core\Repositories\O2oGoodsProductsRepository;
use Illuminate\Http\Request;
use Validator;
use Hash;

class AuthController extends Controller
{
	private $clerk;
	private $test;

	public function __construct(ClerkRepository $repository,
	                            O2oGoodsProductsRepository $o2oGoodsProductsRepository)
	{
		$this->clerk = $repository;
		$this->test  = $o2oGoodsProductsRepository;
	}

	public function issueToken(Request $request)
	{
		$input   = $request->except('_token');

		$rules   = [
			'username' => 'required',
			'password' => 'required',
		];
		$message = [
			"required" => ":attribute 不能为空",
		];

		$attributes = [
			'username' => '用户名',
			'password' => '登录密码',
		];

		$validator = Validator::make($input, $rules, $message, $attributes);
		if ($validator->fails()) {

			return $this->failed($validator->messages()->first());
		}

		$credentials = ['mobile' => $input['username']];
		if (!$user = $this->clerk->getClerkByCredentials($credentials)) {
			return $this->failed('用户不存在');
		}

		if (empty($user->password) || !Hash::check($input['password'], $user->password)) {
			return $this->failed('密码验证失败');
		}

		if ($user->status == 0) {
			return $this->failed('您的账号已被禁用，联系网站管理员或客服！');
		}

		$token = $user->createToken($user->mobile)->accessToken;

		return $this->success(['token_type' => 'Bearer', 'access_token' => $token, 'clerk' => $user]);
	}

}